import json
from flask import Blueprint, request, jsonify
from controllers.common import *
from controllers.db import *

kindom_buff_api = Blueprint('kindom_buff_api', __name__)
kindom_buff_sync_api = Blueprint('kindom_buff_sync_api', __name__)
kindom_buff_schedule_sync_api = Blueprint('kindom_buff_schedule_sync_api', __name__)

@kindom_buff_api.route("/kindom_buff", methods=['POST', 'GET'])
def project_action():
    def get_reward_list():
        doc_data = loadDocument()
        game_data = loadGame()
        result_data = {}
        # buff
        item_type = 109
        result_data[item_type] = []
        for i in doc_data['doc_buff_info']:
            if i in game_data['game_buff_func_info']:
                if game_data['game_buff_func_info'][i]['a3'] == 0:
                    type = 'basic'
                else:
                    type = 'bonus'
                name = doc_data['doc_buff_info'][str(i)]['name']
                price = 100
                tmp = {}
                tmp['value'] = '[' + type + '] ' + name + '-' + str(i)
                tmp['type'] = type
                tmp['id'] = int(i)
                tmp['price'] = price
                result_data[item_type].append(tmp)
        return result_data
    params = json.loads(request.data)
    _action = params['action']
    result_data = {'status': 200, 'data': {'msg': '', 'ret': 0, 'type': 'success', 'env': EVN, 'item': ''}}
    if _action == 'view':
        reward_item_list = rewardList()
        reward_item_list = reward_item_list['name']
        reward_list = get_reward_list()

        query = KindomBuff.query.order_by('id').all()
        result = []
        for q in query:
            _buff = json.loads(q.buff)
            for i in range(len(_buff)):
                # 'a': [109, _buff[i]['a'][0], _buff[i]['a'][1]]
                name = 'Unknown'
                for j in reward_list[109]:
                    if j['id'] == _buff[i]['a'][0]:
                        name = j['value']
                        break

                _buff[i] = {
                    'type': 109,
                    'id': _buff[i]['a'][0],
                    'num': _buff[i]['a'][1],
                    'name': name,
                    'price': 100
                }
            tmp = {
                "id": int(q.id),
                'name': q.name,
                'buff': _buff
            }
            result.append(tmp)
        result_data['data']['item'] = result
    elif _action == 'reward_list':
        reward_list = get_reward_list()
        result = {}
        result['reward'] = reward_list

        return jsonify({'data': result['reward']})
    elif _action == 'delete':
        _id = params['id']
        project_data = KindomBuff.query.filter_by(id=_id).first()
        db.session.delete(project_data)
        db.session.commit()
        project_data = KindomBuff.query.filter_by(id=_id).first()
        if project_data is not None:
            result_data['status'] = 500
            result_data['data']['msg'] = "删除失败：id is not None"
        else:
            result_data['data']['msg'] = "删除成功"
    elif _action == 'remark':
        _name = params['name']
        _id = params['id']
        KindomBuff.query.filter_by(id=_id).update({'name': _name})
        db.session.commit()
        result_data['data']['msg'] = "Remark 更新成功"
    elif _action == 'update':
        _data = params['list']
        for i in _data:
            for j in range(len(i['buff'])):
                i['buff'][j] = {'a': [i['buff'][j]['id'], i['buff'][j]['num']]}

        for i in _data:
            if i['id'] == -1:
                new_data = KindomBuff(
                    name=i['name'],
                    buff=json.dumps(i['buff']),
                )
                db.session.add(new_data)
            else:
                KindomBuff.query.filter_by(id=i['id']).update({
                    "name": i['name'],
                    "buff": json.dumps(i['buff'])
                })
        db.session.commit()
        result_data['data']['msg'] = '更新成功'
    elif _action == 'view_schedule':
        query = KindomBuffSchedule.query.order_by('project').all()
        result = []
        for q in query:
            result.append({
                'project': q.project,
                'begin_time': q.begin_time,
                'end_time': q.end_time,
                "pid": q.pid,
                'sid_list': q.sid_list
            })
        result_data['data']['item'] = result
    elif _action == 'delete_schedule':
        _project = params['project']
        project_data = KindomBuffSchedule.query.filter_by(project=_project).first()
        db.session.delete(project_data)
        db.session.commit()
        project_data = KindomBuffSchedule.query.filter_by(project=_project).first()
        if project_data is not None:
            result_data['status'] = 500
            result_data['data']['msg'] = "删除失败：id is not None"
        else:
            result_data['data']['msg'] = "删除成功"
    elif _action == 'update_schedule':
        _data = params['list']
        for i in _data:
            if i['project'] == -1:
                new_data = KindomBuffSchedule(
                    begin_time=i['begin_time'],
                    end_time=i['end_time'],
                    pid=i['pid'],
                    sid_list=i['sid_list']
                )
                db.session.add(new_data)
            else:
                KindomBuffSchedule.query.filter_by(project=i['project']).update({
                    "begin_time": i['begin_time'],
                    "end_time": i['end_time'],
                    "pid": i['pid'],
                    "sid_list": i['sid_list']
                })
        db.session.commit()

        active_kindom_schedule = {}
        all_schedule = KindomBuffSchedule.query.order_by('project').all()
        all_project = KindomBuff.query.order_by('id').all()
        project_list = {}
        for p in all_project:
            buff = json.loads(p.buff)
            _buff = []
            for b in buff:
                _buff.append([b['a'][0], b['a'][1]])
            project_list[str(p.id)] = _buff
        for s in all_schedule:
            _begin_time = fomat_date_str(s.begin_time)
            _end_time = fomat_date_str(s.end_time)
            if _end_time < int(time.time()):
                continue
            _sid_list = ToSidList(s.sid_list)
            if str(s.pid) in project_list:
                for sid in _sid_list:
                    if str(sid) not in active_kindom_schedule:
                        active_kindom_schedule[str(sid)] = []
                    active_kindom_schedule[str(sid)].append({
                        'begin_time': _begin_time,
                        'end_time': _end_time,
                        'buff': project_list[str(s.pid)]
                    })
        response = DownLoad('common_buff', {
            'active_kindom_schedule': active_kindom_schedule
        }, 1)

        result_data['data']['msg'] = '更新成功'
    elif _action == 'project_list':
        project_data = KindomBuff.query.order_by('id').all()
        result = []
        for i in project_data:
            result.append({
                "value": i.id,
                "label": f"{i.id}_{i.name}"
            })
        return json.dumps(result)
    return jsonify(result_data)


@kindom_buff_sync_api.route('/kindom_buff_sync', methods=['GET', 'POST'])
def kindom_buff_sync():
    data = {}
    with open(STATIC_PATH + '../sync/common_buff_preprocessing.json', encoding='utf8') as f:
        temp_data = json.load(f)
    data = temp_data['RECORDS']
    print('data length:', len(data))
    _currentIndex = 0
    for i in data:
        _currentIndex += 1
        print('handler: ' + str(_currentIndex) + ' / ' + str(len(data)))
        _project = int(i['id'])
        _name = i['name']
        buff = json.loads(i['buff'])
        _buff = []
        for b in buff:
            _buff.append({
                'a': [b[0], b[1]]
            })


        new_project_data = KindomBuff(
            id=_project,
            name=_name,
            buff=json.dumps(_buff),
        )
        db.session.add(new_project_data)
    db.session.commit()
    return jsonify({'msg': 'finished'})


@kindom_buff_schedule_sync_api.route('/kindom_buff_schedule_sync', methods=['GET', 'POST'])
def kindom_buff_schedule_sync():
    data = {}
    with open(STATIC_PATH + '../sync/common_buff_schedule_preprocessing.json', encoding='utf8') as f:
        temp_data = json.load(f)
    data = temp_data['RECORDS']
    print('data length:', len(data))
    _currentIndex = 0
    for i in data:
        _currentIndex += 1
        print('handler: ' + str(_currentIndex) + ' / ' + str(len(data)))
        _project = int(i['id'])
        _begin_time = i['begin_time']
        _end_time = i['end_time']
        _pid = int(i['proj'])
        _sid_list = i['sid_list']



        new_project_data = KindomBuffSchedule(
            project=_project,
            begin_time=_begin_time,
            end_time=_end_time,
            pid=_pid,
            sid_list = _sid_list
        )
        db.session.add(new_project_data)
    db.session.commit()
    return jsonify({'msg': 'finished'})
